package com.hex.campus.backend.hex_campus_backend.service;

import com.hex.campus.backend.hex_campus_backend.entity.User;
import com.hex.campus.backend.hex_campus_backend.repository.UserRepository;
import com.hex.campus.backend.hex_campus_backend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AuthService {

    @Autowired
    private UserRepository userRepository;

    public Optional<User> login(String username, String password) {
        Optional<User> user = userRepository.findByUsername(username);
        if (user.isPresent() && user.get().getPassword().equals(password)) {
            return user;
        }
        return Optional.empty();
    }

    public String generateToken(Long userId) {
        return JwtUtil.generateToken(userId);
    }

    public User register(User user) {
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new RuntimeException("Username already exists");
        }
        return userRepository.save(user);
    }
}